package com.lizhi.yun.core.handler;

import com.lizhi.common.yun.entity.ListResponseResult;
import com.lizhi.rpc.model.RobotStatusManager;
import com.lizhi.utils.StringUtils;
import com.lizhi.utils.json.SamJsonUtil;
import com.lizhi.yun.db.sfrobot.entity.RobotStatus;
import com.lizhi.yun.db.sfrobot.repository.RobotStatusRepo;
import com.lizhi.yun.deploy.NewBaseHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: lizhi
 * @Description:
 * @Date: create in 2020/11/18 11:10
 */
@Slf4j
@Service
public class RobotStatusHandler extends NewBaseHandler {

    @Resource
    private RobotStatusRepo robotStatusRepo;

    public ListResponseResult doMain(String json){
        Map<String, Object> map = SamJsonUtil.toMap(json);
        PageRequest pageRequest = getPageRequestDesc(map, "dataUpTime");

        List<RobotStatus> robotStatuses = RobotStatusManager.getInstance().getRobots();
        String hospitalId = map.get("hospitalId").toString();
        String hospitalIds = "";
        if (!StringUtils.isEmpty(map.get("hospitalIds"))){
            hospitalIds = map.get("hospitalIds").toString();
        }

        if (robotStatuses == null){
            return getListResult(0, new ArrayList<RobotStatus>(), map);
        }
        List<RobotStatus> listRobotStatus = new ArrayList<>();
        for (RobotStatus robotStatus : robotStatuses){
            if (StringUtils.isEmpty(hospitalIds)){
                if (StringUtils.isEmpty(hospitalId)){
                    listRobotStatus.add(robotStatus);
                } else if (hospitalId.equals(robotStatus.getHospitalId())){
                    listRobotStatus.add(robotStatus);
                }
            } else if (hospitalIds.contains(robotStatus.getHospitalId())){
                if (StringUtils.isEmpty(hospitalId)){
                    listRobotStatus.add(robotStatus);
                } else if (hospitalId.equals(robotStatus.getHospitalId())){
                    listRobotStatus.add(robotStatus);
                }
            }
        }
        int start = pageRequest.getPageNumber() * pageRequest.getPageSize();
        int end = start + pageRequest.getPageSize();
        if (end >= listRobotStatus.size()){
            end = listRobotStatus.size();
        }
        List<RobotStatus> list = new ArrayList<>();
        for(int index = start; index < end; index++) {
            RobotStatus robotStatus = listRobotStatus.get(index);
            list.add(robotStatus);
        }
        return getListResult(list.size(), list, map);
    }
}
